<template>
  <div>
    <div class="avatar">
      <van-image :src="avatar" type="contain" />
      <van-uploader :after-read="afterRead" :preview-size="['100%', '100%']" />
    </div>
    <h1 class="username">{{ userStore.userInfo?.username }}</h1>
  </div>
  <van-cell-group>
    <van-cell
      title="个人设置"
      is-link
      arrow-direction="right"
      v-for="item in 6"
    ></van-cell>
  </van-cell-group>
  <div class="btn-cont">
    <van-button type="danger" block @click="handleLogout">退出登录</van-button>
  </div>
</template>

<script setup lang="ts">
import { useUserStore } from "../store/user";
import { useRouter } from "vue-router";
import Cloud from "leancloud-storage";
import { userUpdate } from "../api/user";
import { computed } from "vue";
// import UploaderAfterRead from 'vant'
const userStore = useUserStore();
const router = useRouter();
const handleLogout = () => {
  userStore.userInfo = null;
  router.push("/");
};

//图片上传
interface CallBack {
  (base64: string | ArrayBuffer | null): void;
}
function getBase64(img: File, callback: CallBack) {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result));
  reader.readAsDataURL(img);
}
const afterRead = (item: any) => {
  // console.log(item.file);
  getBase64(item.file, async (base64) => {
    // console.log(base64);
    let res: any = await new Cloud.File("vue-client-2206.png", {
      base64,
    }).save();
    console.log(res);
    let { url } = res.attributes;
    let { objectId, sessionToken } = userStore.userInfo!;
    let update = await userUpdate(objectId, sessionToken, { avatar: url });
    userStore.userInfo!.avatar = url; //更新本地状态机
  });
};

// 获取用户头像链接
const avatar = computed(() => {
  let url = "https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg"; //默认头像
  if (userStore.userInfo && userStore.userInfo.avatar) {
    url = userStore.userInfo.avatar; //自己上传的头像
  }
  return url;
});
</script>

<style lang="scss" scoped>
.username {
  text-align: center;
  font-size: 4rem;
}
.btn-cont {
  padding: 20px;
}
.avatar {
  position: relative;
  .van-uploader {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
  }
  :deep(.van-uploader__wrapper) {
    height: 100%;
    width: 100%;
  }
  .van-uploader__upload {
    height: 100%;
    width: 100%;
  }
}
</style>
